package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.project.domain.dto.LoginRequest;
import com.example.project.domain.entity.User;
import com.example.project.domain.response.Response;
import com.example.project.mapper.UserMapper;
import com.example.project.service.UserService;
import com.example.project.utils.JsonUtil;
import com.example.project.utils.JwtUtil;
import com.example.project.utils.RedisUtil;
import com.example.project.utils.UserContextUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private JsonUtil jsonUtil;

    @Override
    public Response<Void> createUser(User user) {
//        user.setId(UUID.randomUUID().toString());
        userMapper.insert(user);
        return Response.success(null);
    }

    @Override
    public Response<User> getUserById(String id) {
        return Response.success(userMapper.selectById(id));
    }

    @Override
    public Response<String> login(LoginRequest request) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, request.getUsername()));
        if (user == null) {
            return Response.error(400, "用户不存在");
        }
        if (!user.getPassword().equals(request.getPassword())) {
            return Response.error(400, "密码错误");
        }
        // 生成 JWT 并返回
        return Response.success(jwtUtil.generateToken(request.getUsername()));
    }

    @Override
    public Response<User> getUser() {
        // 从缓存中获取用户信息
        String username = UserContextUtil.getUser();
        String cacheData = redisUtil.get("user:" + username);
        if (cacheData != null) {
            // cacheData 转换成 User
            return Response.success(JsonUtil.fromJson(cacheData, User.class));
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        // 存入缓存
        redisUtil.set("user:" + username, JsonUtil.toJson(user), 60 * 60 * 24, TimeUnit.SECONDS);
        return Response.success(user);
    }
}